package vn.ikame.android.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.kxml2.io.KXmlParser;
import org.w3c.dom.Document;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import vn.ikame.android.object.Category;
import vn.ikame.android.object.Chap;
import vn.ikame.android.object.Story;
import android.content.Context;
import android.util.Log;


public class XMLParser {
	Context ctx;
	
	public XMLParser(Context ct){
		this.ctx = ct;
	}
	
	public static ArrayList<Category> getCategoryList(String url) throws Exception{
		ArrayList<Category> qList = new ArrayList<Category>();
        InputStreamReader is = null;

        try {
        	URL myURL = new URL(url);
        	
        	HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(myURL.openStream());
			
			DOMSource source = new DOMSource(document);  
			StringWriter xmlAsWriter = new StringWriter();  
			  
			StreamResult result = new StreamResult(xmlAsWriter);  
			  
			TransformerFactory.newInstance().newTransformer().transform(source, result);
			ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); 
			
           
            is = new InputStreamReader(inputStream, "UTF-8");
            
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        KXmlParser parser = new KXmlParser();
        int iCount = 0;
        try {
        	
            parser.setInput(is); 
            parser.nextTag(); 
            parser.require(XmlPullParser.START_TAG, null, "datas");
            
            
            String name = "", img = "";
            int id = 0;
            
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() == XmlPullParser.START_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                    	name = ""; 
                    	id = 0;
                    	img = "";
                    } else if ("id".equals(tag)) {
                    	id = Integer.valueOf(parser.nextText()); 
                    } else if ("title".equals(tag)) {
                    	name = parser.nextText().trim(); 
                    } else if ("img".equals(tag)) {
                    	img = parser.nextText().trim(); 
                    } 
                    
                } else if (parser.getEventType() == XmlPullParser.END_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                		Category s = new Category(name, img, id);
                    	qList.add(s);
                    	Log.w("HienPL",iCount + ": " + name + " " + " " + img + "  " + id );
                    	
                        iCount++;
                    }
                }
            }
        } catch (XmlPullParserException ex) {
        	System.out.println("er1");
        } catch (IOException ex) {
        	System.out.println("er2");
        }
        return qList;
	}
	
	
	public static ArrayList<Story> getStoryList(String url) throws Exception{
		ArrayList<Story> qList = new ArrayList<Story>();
        InputStreamReader is = null;

        try {
        	URL myURL = new URL(url);

        	HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(myURL.openStream());
			
			DOMSource source = new DOMSource(document);  
			StringWriter xmlAsWriter = new StringWriter();  
			  
			StreamResult result = new StreamResult(xmlAsWriter);  
			  
			TransformerFactory.newInstance().newTransformer().transform(source, result);
			ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); 
			
           
            is = new InputStreamReader(inputStream, "UTF-8");
            
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        KXmlParser parser = new KXmlParser();
        int iCount = 0;
        try {
        	
            parser.setInput(is); 
            parser.nextTag(); 
            parser.require(XmlPullParser.START_TAG, null, "datas");
            
            
            String name = "", author = "";
            int id = 0;

            
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() == XmlPullParser.START_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                    	name = ""; 
                    	id = 0;
                    	author = "";
                    } else if ("id".equals(tag)) {
                    	id = Integer.valueOf(parser.nextText());
                    } else if ("title".equals(tag)) {
                    	name = parser.nextText().trim();
                    } else if ("content".equals(tag)) {
                    	author = parser.nextText().trim();
                    } 
                    
                } else if (parser.getEventType() == XmlPullParser.END_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                    	Story s = new Story(name, id, author);
                    	qList.add(s);
                    	Log.w("HienPL",iCount + " " + name + " " + id + " " + author);
                    	
                        iCount++;
                    }
                }
            }
        } catch (XmlPullParserException ex) {
        	System.out.println("er1");
        } catch (IOException ex) {
        	System.out.println("er2");
        }
        return qList;
	}
	
	
    public static ArrayList<Chap> getChapList(String url) throws Exception {
    	ArrayList<Chap> qList = new ArrayList<Chap>();
        InputStreamReader is = null;

        try {
        	URL myURL = new URL(url);
        	
        	HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
			conn.setConnectTimeout(15000);
			conn.setReadTimeout(15000);
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(myURL.openStream());
			
			DOMSource source = new DOMSource(document);  
			StringWriter xmlAsWriter = new StringWriter();  
			  
			StreamResult result = new StreamResult(xmlAsWriter);  
			  
			TransformerFactory.newInstance().newTransformer().transform(source, result);
			ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); 
			
           
            is = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        KXmlParser parser = new KXmlParser();
        try {
            parser.setInput(is);
            parser.nextTag();
            parser.require(XmlPullParser.START_TAG, null, "datas");
            
            String storyName = "", chapName = "";
            int id = 0;
            
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() == XmlPullParser.START_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                    	storyName = ""; 
                    	chapName = "";
                    	id = 0;
                    } else if ("storyname".equals(tag)) {
                    	storyName = parser.nextText().trim();
                    } else if ("title".equals(tag)) {
                    	chapName = parser.nextText().trim();
                    } else if ("id".equals(tag)) {
                    	id = Integer.valueOf(parser.nextText().trim());
                    } 
                    
                } else if (parser.getEventType() == XmlPullParser.END_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                    	
                    	Chap s = new Chap(storyName, chapName, id);
                    	qList.add(s);
                    }
                }
            }
        } catch (XmlPullParserException ex) {
        } catch (IOException ex) {
        }
        return qList;
    }
    
    public static String getcontent(String url) throws Exception {
    	String content = "";
        InputStreamReader is = null;

        try {
        	URL myURL = new URL(url);
        	
        	HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
			conn.setConnectTimeout(15000);
			conn.setReadTimeout(15000);
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(myURL.openStream());
			
			DOMSource source = new DOMSource(document);  
			StringWriter xmlAsWriter = new StringWriter();  
			  
			StreamResult result = new StreamResult(xmlAsWriter);  
			  
			TransformerFactory.newInstance().newTransformer().transform(source, result);
			ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); 
			
           
            is = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        KXmlParser parser = new KXmlParser();
        try {
            parser.setInput(is);
            parser.nextTag();
            parser.require(XmlPullParser.START_TAG, null, "datas");
            
            
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() == XmlPullParser.START_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                    	content = ""; 
                    } else if ("content".equals(tag)) {
                    	content = parser.nextText().trim();
                    } 

                	Log.w("HienPL", content);
                    
                } else if (parser.getEventType() == XmlPullParser.END_TAG) {
                    String tag = parser.getName();
                    if ("data".equals(tag)) {
                    	
                    	
                    }
                }
            }
        } catch (XmlPullParserException ex) {
        } catch (IOException ex) {
        }
        return content;
    }
}
